import React, { memo, forwardRef, useImperativeHandle, useState, useEffect, useRef, useCallback } from 'react';

interface GridCellEditWrapperProps {
  onBlur?: () => void;
  visible?: boolean;
  autoFocus?: boolean;
  children?: React.ReactNode | React.ReactNode[];
  className?: string;
  style?: React.CSSProperties;
}

const GridCellEditWrapper: React.FC<GridCellEditWrapperProps> = forwardRef((props, ref: any) => {
  const { autoFocus, children, visible, onBlur, className, style } = props;
  const [foucs, setFoucs] = useState(autoFocus);
  const visibleRef = useRef<boolean | undefined>(visible);
  const divRef = useRef<HTMLDivElement>(null);

  const handleEvent = useCallback(
    (event: MouseEvent) => {
      const target: any = event.target;
      if (visibleRef.current) return;

      const include = divRef.current?.contains(target);
      if (include && !foucs) setFoucs(true);
      if (!include && foucs) {
        setFoucs(false);
        onBlur && onBlur();
      }
    },
    [onBlur, foucs],
  );

  useEffect(() => {
    visibleRef.current = visible;
  }, [visible]);

  useImperativeHandle(
    ref,
    () => ({
      focus: () => {
        setFoucs(true);
      },
      blur: () => {
        setFoucs(false);
      },
    }),
    [],
  );

  useEffect(() => {
    window.addEventListener('mousedown', handleEvent);
    return () => {
      window.removeEventListener('mousedown', handleEvent);
    };
  }, []);

  return (
    <div className={className} style={style} ref={divRef}>
      {children}
    </div>
  );
});

export default memo(GridCellEditWrapper);
